import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux'
import { Modal, Form, Input, InputNumber, notification, Icon, DatePicker, message } from 'antd'
const { TextArea } = Input;
import moment from 'moment'
const FormItem = Form.Item;
import Chooser from 'components/chooser'
import confirmPaymentService from 'containers/financial-management/confirm-payment/confirm-payment.service'
import baseService from 'share/base.service'
import config from "config";

//选择付款账户
class CompanyBankSelector extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false ,
      currencyList: [],
      paymentChequeNoDisable:true,
      selectorItem:{
        title: messages('financial-management.key147'/*公司银行账号*/),
        url: `${config.baseUrl}/api/CompanyBank/getAuthCompanyBank/${props.user.userOID}`,
        searchForm: [],
        columns: [
          { title: messages('financial-management.key148'/*账号名称*/), dataIndex: 'bankAccountName' },
          { title: messages('financial-management.key149'/*付款账号*/), dataIndex: 'bankAccountNumber' },
          { title: messages('financial-management.key150'/*银行名称*/), dataIndex: 'bankName' }
        ],
        key: 'companyBank.bankAccountNumber'
      },
      paymentTypeDisabled: true,
      paymentParams: {},
      paymentTime: new Date().format('yyyy-MM-dd')
    };
  }

  componentWillMount(){
    this.getSystemValueList(2105).then(res => {
      this.setState({paymentTypeMethods: {
        fetched: true,
        data: res.data.values
      }})
    });
    baseService.getAllCurrencyByLanguage().then(res => {
      this.setState({currencyList: res.data})
    })
  }

  handleOk = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let account = values.paymentBankAccount[0];
        let result = {
          ...this.props.data,
          paymentBankAccount: account.bankAccountNumber,
          paymentBankCity: account.city,
          paymentCurrency: values.paymentCurrency,
          paymentExchangeRate: values.paymentExchangeRate,
          paymentName: account.bankAccountName,
          paymentOpeningBank: account.bankName,
          paymentOperatorNumber: account.bankCode,
          paymentRemark: values.paymentRemark,
          paymentType: values.paymentType[0].description,
          paymentCode: values.paymentType[0].paymentMethodCode,
          paymentCategory: values.paymentType[0].paymentMethodCategory,
          paymentChequeNo: values.paymentChequeNo,
          paymentTime: new Date(values.paymentTime).format('yyyy-MM-dd') === new Date().format('yyyy-MM-dd') ? new Date().format('yyyy-MM-dd hh:mm:ss') : new Date(values.paymentTime).format('yyyy-MM-dd 23:59:59')
        };
        this.setState({ loading: true });
        if(this.props.status === 'prending_pay'){
          result.accountCode = account.accountCode;
        }
        confirmPaymentService.confirmPayment(this.props.status, result).then(res => {
          this.setState({ loading: false });
          this.props.onOk(res.data);
        }).catch((e)=>{
          this.setState({loading: false});
          if (e.response.data && e.response.data.message) {
            notification.open({
              message: messages('financial-management.key587')/*支付错误*/,
              description: e.response.data.message,
              icon: <Icon type="frown-circle" style={{color: '#e93652'}}/>,
            });
            return;
          }
          if(e.name === 'SyntaxError')
            this.props.onOk();
          else
            notification.open({
              message: messages('financial-management.key151'/*确认付款失败*/),
              description: messages('common.error'),
              icon: <Icon type="frown-circle" style={{ color: '#e93652' }} />,
            });
        })
      }
    });
  };

  handleChangeAccount = (result) => {
    const { currencyList } = this.state;
    let companyBank = result.length > 0 ? result[0] : null;
    if(companyBank){
      let targetCurrencyCode = companyBank.currencyCode;
      let rate = 1;
      currencyList.map(item => {
        if(item.currency === targetCurrencyCode)
          rate = item.rate;
      });
      this.setState({
        paymentTypeDisabled: false,
        paymentParams: {id:companyBank.id}
      });
      confirmPaymentService.getPayType(companyBank.id).then(res => {
        this.props.form.setFieldsValue({
          paymentCurrency: targetCurrencyCode,
          paymentExchangeRate: rate,
          paymentType: res.data.length ? res.data : undefined });
      }).catch(() => {
        this.props.form.setFieldsValue({ paymentCurrency: targetCurrencyCode, paymentExchangeRate: rate });
        message.error(messages('financial-management.key566')/*系统异常*/);
      });
    }else{
      this.props.form.setFieldsValue({paymentType: ''});
      this.setState({
        paymentTypeDisabled: true,
        paymentParams: {}
      });
    }
  };

  paymentTypeCallback = (valueList) =>{
    if(valueList[0] && valueList[0].paymentMethodCode==='PAY_IN_CHEQUE'){
      this.setState({paymentChequeNoDisable:false});
    }else{
      this.props.form.setFieldsValue({paymentChequeNo:null});
      this.setState({paymentChequeNoDisable:true});
    }
  };

  changeDateTime = (value) => {
    this.setState({paymentTime: new Date(value).format('yyyy-MM-dd')});
  };

  render() {
    const { loading,paymentChequeNoDisable,selectorItem,paymentTypeDisabled,paymentParams } = this.state;
    const { visible, onCancel, selectedDataItems } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14, offset: 1 },
    };
    let record = selectedDataItems.length > 0 ? selectedDataItems[0] : {};
    return (
      <Modal visible={visible} onCancel={onCancel} onOk={this.handleOk} title={messages('financial-management.key152'/*支付确认*/)} confirmLoading={loading}>
        <Form>
          <FormItem {...formItemLayout} label={messages('financial-management.key153'/*付款日期*/)}>
            {getFieldDecorator('paymentTime', {
              rules: [{
                required: true,
                message: messages('common.name.is.required', {name: messages('financial-management.key153'/*付款日期*/)})
              }],
              initialValue: moment(new Date())
            })(
              <DatePicker format={'YYYY-MM-DD'}
                          onChange={this.changeDateTime}
                          style={{width:'100%'}}/>
            )}
          </FormItem>
        </Form>
        <Form>
          <FormItem {...formItemLayout} label={messages('financial-management.key154'/*付款账号*/)}>
            {getFieldDecorator('paymentBankAccount', {
              rules: [{
                required: true,
                message: messages('common.name.is.required', {name: messages('financial-management.key154'/*付款账号*/)})
              }]
            })(
              <Chooser valueKey="bankAccountNumber"
                       selectorItem={selectorItem}
                       listExtraParams={{
                         setOfBooksId: record.setOfBooksId,
                         currency: record.currencyCode
                       }}
                       labelKey="bankAccountName"
                       single onChange={this.handleChangeAccount}/>
            )}
          </FormItem>
        </Form>
        <Form>
          <FormItem {...formItemLayout} label={messages('financial-management.key155'/*币种*/)}>
            {getFieldDecorator('paymentCurrency')(
              <Input disabled/>
            )}
          </FormItem>
        </Form>
        <Form>
          <FormItem {...formItemLayout} label={messages('financial-management.key156'/*付款方式*/)}>
            {getFieldDecorator('paymentType', {
              rules: [{
                required: true,
                message: messages('common.name.is.required', {name: messages('financial-management.key156'/*付款方式*/)})
              }]
            })(
              <Chooser type="payment_type"
                       single
                       labelKey="description"
                       listExtraParams={paymentParams}
                       disabled={paymentTypeDisabled}
                       onChange={this.paymentTypeCallback}
                       valueKey="paymentMethodCode"/>
            )}
          </FormItem>
        </Form>
        <Form>
          <FormItem {...formItemLayout} label={messages('financial-management.key157'/*汇率*/)}>
            {getFieldDecorator('paymentExchangeRate')(
              <Input disabled/>
            )}
          </FormItem>
        </Form>
        <Form>
          <FormItem {...formItemLayout} label={messages('financial-management.key158'/*支票号*/)}>
            {getFieldDecorator('paymentChequeNo',
              {
                rules: [{
                  required: !paymentChequeNoDisable,
                  message: messages('common.name.is.required', {name: messages('financial-management.key158'/*支票号*/)})
                }]
              }
            )(
              <InputNumber  style={{width:'100%'}} precision={0} step={0} maxLength="8"  disabled={paymentChequeNoDisable}/>
            )}
          </FormItem>
        </Form>
        <Form>
          <FormItem {...formItemLayout} label={messages('financial-management.key159'/*备注*/)}>
            {getFieldDecorator('paymentRemark')(
              <TextArea maxLength="200"/>
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  }
}

CompanyBankSelector.propTypes = {
  visible: React.PropTypes.bool,
  onCancel: React.PropTypes.func,
  onOk: React.PropTypes.func,
  afterClose: React.PropTypes.func,
  data: React.PropTypes.object,
  selectedDataItems: React.PropTypes.array
};

CompanyBankSelector.defaultProps = {
  onOk: () => {},
  onCancel: () => {},
  afterClose: () => {},
  selectedDataItems: []
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user:state.login.user
  }
}

const WrappedCompanyBankSelector = Form.create()(CompanyBankSelector);

export default connect(mapStateToProps)(WrappedCompanyBankSelector);
